package com.bestcem.xm.member.grpc.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.common.core.uitls.EnumUtil;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import com.bestcem.xm.member.grpc.service.param.member.*;
import com.bestcem.xm.member.grpc.v1.common.ExtendFieldValue;
import com.bestcem.xm.member.grpc.v1.common.*;
import com.bestcem.xm.member.grpc.v1.enums.MemberTypeEnum;
import com.bestcem.xm.member.grpc.v1.services.*;
import com.bestcem.xm.member.service.FuzzyMemberService;
import com.bestcem.xm.member.service.MemberService;
import com.bestcem.xm.member.service.WechatService;
import com.bestcem.xm.member.service.dto.MemberDTO;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 联系人相关grpc服务
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/7/16
 */
@Slf4j
@GrpcService
public class MemberGrpcService extends MemberServiceGrpc.MemberServiceImplBase {

    @Resource
    private MemberService memberService;

    @Resource
    private FuzzyMemberService fuzzyMemberService;

    @Resource
    private WechatService wechatService;

    /**
     * 批量删除联系人 软删除
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void deleteMembers(DeleteMembersRequest request, StreamObserver<BatchDeleteResponse> responseObserver) {
        BatchDeleteResponse.Builder builder = BatchDeleteResponse.newBuilder();

        // 组装参数
        DeleteMembersParam param = requestToDeleteMembersParam(request);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 联系人删除
        ServiceResult<Integer> result = memberService.deleteMembers(param);
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setDeleteCount(result.getData());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据id获取联系人信息
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void getMember(GetMemberRequest request, StreamObserver<GetMemberResponse> responseObserver) {
        GetMemberResponse.Builder builder = GetMemberResponse.newBuilder();

        // 组装参数
        GetMemberParam param = requestToGetMemberDetailParam(request);

        // 参数校验
        /*Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }*/

        // 获取联系人信息
        ServiceResult<MemberDTO> result = memberService.getMemberDetail(param);

        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setMember(dtoToMember(result.getData()));
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 更新联系人
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void updateMember(UpdateMemberRequest request, StreamObserver<UpdateResponse> responseObserver) {
        UpdateResponse.Builder builder = UpdateResponse.newBuilder();

        // 组装参数
        UpdateMemberParam param = requestToUpdateMemberParam(request);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 获取联系人信息
        ServiceResult<String> result = memberService.updateMember(param);

        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setId(result.getData());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据过滤条件返回联系人id和name
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void listMembersByFilterParam(ListMembersByFilterParamRequest request, StreamObserver<ListMembersByFilterParamResponse> responseObserver) {
        ListMembersByFilterParamResponse.Builder builder = ListMembersByFilterParamResponse.newBuilder();

        ListMemberInfoByFilterParamsParam param = requestToListMemberInfoByFilterParamsParam(request);
        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        // 根据过滤条件返回联系人id和name
        ServiceResult<List<MemberDTO>> result = fuzzyMemberService.listMemberInfoByFilterParams(param);

        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            List<MemberDTO> data = result.getData();
            if (CollUtil.isNotEmpty(data)) {
                builder.addAllMembers(data.stream().map(d -> {
                    Member.Builder memberBuilder = Member.newBuilder();
                    memberBuilder.setName(d.getName());
                    memberBuilder.setId(d.getId());
                    return memberBuilder.build();
                }).collect(Collectors.toList()));
            }
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void listMembersByDeliverParam(ListMembersByDeliverParamRequest request, StreamObserver<ListMembersByDeliverParamResponse> responseObserver) {

        ListMembersByDeliverParamResponse.Builder builder = ListMembersByDeliverParamResponse.newBuilder();

        ListMemberInfoByFilterParamsParam param = requestTolistMembersByDeliverParam(request);
        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        // 根据过滤条件返回联系人id和name
        ServiceResult<List<MemberDTO>> result = fuzzyMemberService.listMemberInfoByFilterParams(param);

        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            List<MemberDTO> data = result.getData();
            if (CollUtil.isNotEmpty(data)) {
                builder.addAllMembers(data.stream().map(d -> {
                    Member.Builder memberBuilder = Member.newBuilder();
                    memberBuilder.setName(d.getName());
                    memberBuilder.setId(d.getId());
                    return memberBuilder.build();
                }).collect(Collectors.toList()));
            }
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


    @Override
    public void listMembersByWx(ListMembersByWxRequest request, StreamObserver<ListMembersByWxResponse> responseObserver) {
        ListMembersByWxResponse.Builder builder = ListMembersByWxResponse.newBuilder();
        ListMembersByWxParam param = requestToListMembersByWxParam(request);
        if (log.isInfoEnabled()) {
            log.info("ListMembersByWxParam {}", param);
        }
        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 根据过滤条件返回联系人id和name
        ServiceResult<List<MemberDTO>> result = memberService.listMembersByWx(param);

        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            List<MemberDTO> memberDTOS = result.getData();
            if (CollUtil.isNotEmpty(memberDTOS)) {
                builder.addAllMembers(memberDTOS.stream().map(this::dtoToMember).collect(Collectors.toList()));
            }
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();

    }

    private ListMembersByWxParam requestToListMembersByWxParam(ListMembersByWxRequest request) {

        if (log.isInfoEnabled()) {
            log.info("ListMembersByWxRequest {}", request);
        }
        ListMembersByWxParam param = new ListMembersByWxParam();
        param.setMemberType(request.getMemberType().getNumber());
        param.setOrgId(request.getOrgId());
        param.setStatus(request.getStatusValue());
        List<MemberQueryParam> queryParamsList = request.getQueryParamsList();
        if (CollUtil.isNotEmpty(queryParamsList)) {
            List<MemberQuery> memberQueries = new ArrayList<>();
            queryParamsList.forEach( item -> {
                MemberQuery memberQuery = new MemberQuery();
                memberQuery.setAppId(item.getAppId());
                memberQuery.setOpenId(item.getOpenId());
                memberQueries.add(memberQuery);
            });
            param.setQueryParams(memberQueries);
        }
        return param;
    }

    private ListMemberInfoByFilterParamsParam requestTolistMembersByDeliverParam(ListMembersByDeliverParamRequest request) {
        ListMemberInfoByFilterParamsParam param = new ListMemberInfoByFilterParamsParam();
        param.setOrgId(request.getOrgId());
        param.setParam(request.getCondition());
        param.setUserId(request.getUserId());
        param.setSuperAdmin(request.getSuperAdmin());
        param.setSeniorAdmin(request.getSeniorAdmin());
        return param;
    }

    /**
     * 获取组织下指定类型的联系人（激活的）数量
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void countOrgMember(CountOrgMemberRequest request, StreamObserver<CountOrgMemberResponse> responseObserver) {
        CountOrgMemberResponse.Builder builder = CountOrgMemberResponse.newBuilder();
        // 组装参数
        CountOrgMemberParam param = requestToCountOrgMemberParam(request);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        // 获取该组织下 指定联系人的数量
        ServiceResult<Long> result = memberService.countOrgMember(param);

        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setTotal(result.getData().intValue());
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();

    }

    /**
     * request to CountOrgMemberParam
     *
     * @param request
     * @return
     */
    private CountOrgMemberParam requestToCountOrgMemberParam(CountOrgMemberRequest request) {
        CountOrgMemberParam param = new CountOrgMemberParam();
        // 组织id
        param.setOrgId(request.getOrgId());
        // 联系人类型
        param.setMemberType(request.getMemberTypeValue());
        return param;
    }

    private ListMemberInfoByFilterParamsParam requestToListMemberInfoByFilterParamsParam(ListMembersByFilterParamRequest request) {
        ListMemberInfoByFilterParamsParam param = new ListMemberInfoByFilterParamsParam();
        param.setOrgId(request.getOrgId());
        param.setParam(request.getCondition());
        param.setUserId(request.getUserId());
        param.setSuperAdmin(request.getSuperAdmin());
        param.setSeniorAdmin(request.getSeniorAdmin());
        return param;
    }

    /**
     * 通过Id获取联系人列表
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void getMemberById(GetMemberByIdRequest request, StreamObserver<GetMemberResponse> responseObserver) {
        GetMemberResponse.Builder builder = GetMemberResponse.newBuilder();

        GetMemberByIdParam param = requestToGetMemberByIdParam(request);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 获取联系人信息
        ServiceResult<MemberDTO> result = memberService.getMemberById(param);

        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setMember(dtoToMember(result.getData()));
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据id列表获取联系人泪飙
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void listMembersByIds(ListMembersByIdsRequest request, StreamObserver<ListMembersByParamResponse> responseObserver) {
        ListMembersByParamResponse.Builder builder = ListMembersByParamResponse.newBuilder();

        ListMemberByIdsParam param = requestToListMemberByIdsParam(request);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 获取联系人信息
        ServiceResult<List<MemberDTO>> result = memberService.listMembersByIds(param);

        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            List<MemberDTO> memberDTOS = result.getData();
            if (CollUtil.isNotEmpty(memberDTOS)) {
                builder.addAllMembers(memberDTOS.stream().map(this::dtoToMember).collect(Collectors.toList()));
            }
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 通过联系人各种信息获取联系人列表
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void listMembersByParam(ListMembersByParamRequest request, StreamObserver<ListMembersByParamResponse> responseObserver) {
        ListMembersByParamResponse.Builder builder = ListMembersByParamResponse.newBuilder();
        ListMembersByParamParam paramParam = new ListMembersByParamParam();
        paramParam.setParam(request.getParam());
        ServiceResult<List<MemberDTO>> result = memberService.listMembersByParam(paramParam);
        if (result.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            List<MemberDTO> memberDTOS = result.getData();
            if (CollUtil.isNotEmpty(memberDTOS)) {
                builder.addAllMembers(memberDTOS.stream().map(memberDTO ->
                        dtoToMember(memberDTO)).collect(Collectors.toList()));
            }
        } else {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void checkDisplayRangePermission(CheckDisplayRangePermissionRequest request, StreamObserver<CheckDisplayRangePermissionResponse> responseObserver) {
        CheckDisplayRangePermissionResponse.Builder builder = CheckDisplayRangePermissionResponse.newBuilder();

        // 参数
        CheckDisplayRangePermParam param = new CheckDisplayRangePermParam();
        param.setOrgId(request.getOrgId());
        param.setUserId(request.getUserId());
        param.setMemberId(request.getMemberId());

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<Boolean> result = memberService.checkUserDisplayRangePerm(param);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            builder.setValid(Boolean.FALSE);
        } else {
            builder.setStatus(RpcStatusResult.success());
            builder.setValid(result.getData());
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void checkDisplayRangePermissionByMemberType(CheckDisplayRangePermissionByMemberTypeRequest request, StreamObserver<CheckDisplayRangePermissionResponse> responseObserver) {
        CheckDisplayRangePermissionResponse.Builder builder = CheckDisplayRangePermissionResponse.newBuilder();

        // 参数
        CheckDisplayRangePermByMemberTypeParam param = new CheckDisplayRangePermByMemberTypeParam();
        param.setOrgId(request.getOrgId());
        param.setUserId(request.getUserId());
        com.bestcem.xm.member.enums.MemberTypeEnum memberTypeEnum = this.mappingMemberType(request.getMemberType());
        param.setMemberTypeEnum(memberTypeEnum);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<Boolean> result = memberService.checkUserDisplayRangePermByMemberType(param);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            builder.setValid(Boolean.FALSE);
        } else {
            builder.setStatus(RpcStatusResult.success());
            builder.setValid(result.getData());
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void importDeliverMember(ImportDeliverMemberRequest request, StreamObserver<ImportDeliverMemberResponse> responseObserver) {
        ImportDeliverMemberResponse.Builder builder = ImportDeliverMemberResponse.newBuilder();
        log.info("开始导入联系人：{}", request);

        // 参数
        ImportDeliverMemberParam param = new ImportDeliverMemberParam();
        param.setOrgId(request.getOrgId());
        param.setDeliverId(request.getDeliverId());
        param.setPrimaryKey(request.getPrimaryKey());

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            log.info("参数异常：{}", violation);
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<List<String>> result = memberService.importDeliverMember(param);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
        } else {
            builder.setStatus(RpcStatusResult.success());
            builder.addAllMemberIds(result.getData());
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * request to ListMemberByIdsParam
     *
     * @param request
     * @return
     */
    private ListMemberByIdsParam requestToListMemberByIdsParam(ListMembersByIdsRequest request) {
        ListMemberByIdsParam param = new ListMemberByIdsParam();
        param.setIds(request.getIdsList());
        return param;
    }

    /**
     * request to GetMemberByIdParam
     *
     * @param request
     * @return
     */
    private GetMemberByIdParam requestToGetMemberByIdParam(GetMemberByIdRequest request) {
        GetMemberByIdParam param = new GetMemberByIdParam();
        param.setId(request.getId());
        return param;
    }

    /**
     * dto 转 Member
     *
     * @param data
     * @return
     */
    private List<Member> dtoToMembers(List<MemberDTO> data) {
        List<Member> members = new ArrayList<>();
        if (CollUtil.isNotEmpty(data)) {
            data.forEach(d -> {
                Member.Builder builder = Member.newBuilder();
                builder.setId(d.getId());
                builder.setName(d.getName());
                builder.setPhone(d.getMobile());
                builder.setEmail(d.getEmail());
                members.add(builder.build());
            });
        }
        return members;
    }

    /**
     * dto 转 Member
     *
     * @param data
     * @return
     */
    private Member dtoToMember(MemberDTO data) {
        Member.Builder builder = Member.newBuilder();
        if (ObjectUtil.isNotEmpty(data)) {
            // bugfix 去除默认值
            // GRpcUtil.fillDefaultValue(data);
            if (StrUtil.isNotEmpty(data.getId())) {
                builder.setId(data.getId());
            }
            if (StrUtil.isNotEmpty(data.getOrgId())) {
                builder.setOrgId(data.getOrgId());
            }
            if (StrUtil.isNotEmpty(data.getSysId())) {
                builder.setSysId(data.getSysId());
            }
            if (ObjectUtil.isNotEmpty(data.getMemberType())) {
                builder.setMemberTypeValue(data.getMemberType());
            }
            if (ObjectUtil.isNotEmpty(data.getStatus())) {
                builder.setStatusValue(data.getStatus());
            }
            // fixme builder.setSource(data.getSource());
            if (StrUtil.isNotEmpty(data.getName())) {
                builder.setName(data.getName());
            }
            if (StrUtil.isNotEmpty(data.getEmail())) {
                builder.setEmail(data.getEmail());
            }
            if (StrUtil.isNotEmpty(data.getMobile())) {
                builder.setPhone(data.getMobile());
            }
            if (StrUtil.isNotEmpty(data.getGender())) {
                builder.setGender(data.getGender());
            }
            if (StrUtil.isNotEmpty(data.getNickname())) {
                builder.setNickname(data.getNickname());
            }
            if (StrUtil.isNotEmpty(data.getRegion())) {
                builder.setRegion(data.getRegion());
            }
            if (StrUtil.isNotEmpty(data.getStore())) {
                builder.setStoreId(data.getStore());
            }
            if (StrUtil.isNotEmpty(data.getContent())) {
                builder.setComment(data.getContent());
            }
            if (StrUtil.isNotEmpty(data.getOpenId())) {
                builder.setOpenId(data.getOpenId());
            }
            if (StrUtil.isNotEmpty(data.getAppId())) {
                builder.setAppId(data.getAppId());
            }
            if (StrUtil.isNotEmpty(data.getUnionId())) {
                builder.setUnionId(data.getUnionId());
            }
            if (StrUtil.isNotEmpty(data.getAlipayUserId())) {
                builder.setAlipayUserId(data.getAlipayUserId());
            }
            if (StrUtil.isNotEmpty(data.getMemberNo())) {
                builder.setMemberNo(data.getMemberNo());
            }
            if (CollUtil.isNotEmpty(data.getAddress())) {
                builder.addAllAddresses(data.getAddress());
            }
            if (StrUtil.isNotEmpty(data.getEmployeeId())) {
                builder.setEmployeeId(data.getEmployeeId());
            }
            if (ObjectUtil.isNotEmpty(data.getBirthday())) {
                builder.setBirthday(GRpcUtil.getTimestamp(data.getBirthday()));
            }
            if (StrUtil.isNotEmpty(data.getDepartment())) {
                builder.setDepartmentName(data.getDepartment());
            }
            if (StrUtil.isNotEmpty(data.getOutNo())) {
                builder.setOutNo(data.getOutNo());
            }
            if (StrUtil.isNotEmpty(data.getPosition())) {
                builder.setPositionName(data.getPosition());
            }
            if (StrUtil.isNotEmpty(data.getInstituteName())) {
                builder.setInstituteName(data.getInstituteName());
            }
            if (StrUtil.isNotEmpty(data.getInstituteId())) {
                builder.setInstituteId(data.getInstituteId());
            }
            if (CollUtil.isNotEmpty(data.getFieldValList())) {
                builder.addAllFieldValues(data.getFieldValList().stream().map(field -> {
                    ExtendFieldValue.Builder fieldBuilder = ExtendFieldValue.newBuilder();
                    GRpcUtil.fillDefaultValue(field);
                    fieldBuilder.setId(field.getId());
                    fieldBuilder.setName(field.getName());
                    fieldBuilder.setTypeValue(field.getType());
                    fieldBuilder.setValue(field.getValue());
                    return fieldBuilder.build();
                }).collect(Collectors.toList()));
            }
            if (StrUtil.isNotEmpty(data.getUserId())) {
                builder.setUserId(data.getUserId());
            }
            if (ObjectUtil.isNotEmpty(data.getAge())) {
                builder.setAge(data.getAge());
            }
            if (CollUtil.isNotEmpty(data.getLabelValueIds())) {
                builder.addAllLabelValues(data.getLabelValueIds().stream().map(label -> {
                    LabelValue.Builder labelBuilder = LabelValue.newBuilder();
                    GRpcUtil.fillDefaultValue(label);
                    labelBuilder.setId(label.getId());
                    labelBuilder.setLabelId(label.getLabelId());
                    return labelBuilder.build();
                }).collect(Collectors.toList()));
            }
        }
        return builder.build();
    }

    /**
     * 查询联系人类型值对应的Grpc联系人类型枚举
     * @param memberType 联系人类型值
     * @author dc.wang <dc.wang@idiaoyan.com>
     * @date 2021/9/13
     */
    private MemberTypeEnum.MemberType mappingGrpcMemberType(Integer memberType){
        if(memberType == null){
            return null;
        }
        com.bestcem.xm.member.enums.MemberTypeEnum memberTypeEnum = EnumUtil.getEnumByIndex(com.bestcem.xm.member.enums.MemberTypeEnum.class, memberType);

        switch (memberTypeEnum){
            case  INDIVIDUAL: return MemberTypeEnum.MemberType.INDIVIDUAL;
            case  INSTITUTION: return MemberTypeEnum.MemberType.INSTITUTION;
            case  INTERIOR: return MemberTypeEnum.MemberType.INTERIOR;
        }
        return null;
    }

    /**
     * 查询Grpc联系人类型值对应的联系人类型枚举
     * @param memberType grpc联系人类型枚举
     * @author dc.wang <dc.wang@idiaoyan.com>
     * @date 2021/9/13
     */
    private com.bestcem.xm.member.enums.MemberTypeEnum mappingMemberType(MemberTypeEnum.MemberType memberType){
        if(memberType == null){
            return null;
        }

        switch (memberType){
            case  INDIVIDUAL: return com.bestcem.xm.member.enums.MemberTypeEnum.INDIVIDUAL;
            case  INTERIOR: return com.bestcem.xm.member.enums.MemberTypeEnum.INTERIOR;
            case  INSTITUTION: return com.bestcem.xm.member.enums.MemberTypeEnum.INSTITUTION;

        }
        return null;
    }

    private Member dtoToMember(OpenPlatformMemberParam data) {
        Member.Builder builder = Member.newBuilder();
        if (ObjectUtil.isNotEmpty(data)) {
            GRpcUtil.fillDefaultValue(data);
            builder.setId(data.getId());
            builder.setOrgId(data.getOrgId());
            builder.setSysId(data.getSysId());
            // fixme builder.setSource(data.getSource());
            builder.setName(data.getName());
            builder.setEmail(data.getEmail());
            builder.setPhone(data.getMobile());
            builder.setGender(data.getGender());
            builder.setNickname(data.getName());
            builder.setRegion(data.getRegion());
            builder.setStoreId(data.getStore());
            builder.setComment(data.getContent());
            builder.setOpenId(data.getOpenId());
            builder.setAppId(data.getAppId());
            builder.setAlipayUserId(data.getAlipayUserId());
            builder.setMemberNo(data.getMemberNo());
            builder.addAllAddresses(data.getAddress());
            builder.setEmployeeId(data.getEmployeeId());
            if (ObjectUtil.isNotEmpty(data.getBirthday())) {
                builder.setBirthday(GRpcUtil.getTimestamp(data.getBirthday()));
            }
            builder.setDepartmentName(data.getDepartment());
            builder.setPositionName(data.getPosition());
            builder.setInstituteName(data.getInstituteName());
            builder.setInstituteId(data.getInstituteId());
            if (CollUtil.isNotEmpty(data.getFieldValues())) {
                builder.addAllFieldValues(data.getFieldValues().stream().map(field -> {
                    ExtendFieldValue.Builder fieldBuilder = ExtendFieldValue.newBuilder();
                    GRpcUtil.fillDefaultValue(field);
                    fieldBuilder.setId(field.getId());
                    fieldBuilder.setName(field.getName());
                    fieldBuilder.setTypeValue(field.getType());
                    fieldBuilder.setValue(field.getValue());
                    return fieldBuilder.build();
                }).collect(Collectors.toList()));
            }
            builder.setUserId(data.getUserId());
            builder.setAge(data.getAge());
            if (CollUtil.isNotEmpty(data.getLabels())) {
                builder.addAllLabelValues(data.getLabels().stream().map(label -> {
                    LabelValue.Builder labelBuilder = LabelValue.newBuilder();
                    GRpcUtil.fillDefaultValue(label);
                    labelBuilder.setId(label.getId());
                    labelBuilder.setLabelId(label.getLabelId());
                    return labelBuilder.build();
                }).collect(Collectors.toList()));
            }
        }
        return builder.build();
    }

    /**
     * request To UpdateMemberParam
     *
     * @param request
     * @return
     */
    private UpdateMemberParam requestToUpdateMemberParam(UpdateMemberRequest request) {
        UpdateMemberParam param = new UpdateMemberParam();
        param.setOrgId(request.getOrgId());
        param.setId(request.getId());
        param.setUserId(request.getUserId());

        Member member = request.getMember();
        if (ObjectUtil.isNotEmpty(member)) {
            param.setSysId(member.getSysId());
            // fixme param.setSource(member.getSource());
            param.setName(member.getName());
            param.setEmail(member.getEmail());
            param.setMobile(member.getPhone());
            param.setGender(member.getGender());
            param.setNickname(member.getNickname());
            param.setRegion(member.getRegion());
            param.setStore(member.getStoreId());
            param.setContent(member.getComment());
            param.setOpenId(member.getOpenId());
            param.setAlipayUserId(member.getAlipayUserId());
            param.setMemberNo(member.getMemberNo());

            param.setAddress(member.getAddressesList());
            param.setEmployeeId(member.getEmployeeId());
            param.setEmployeeStatus(member.getEmployeeStatusValue());
            param.setMemberType(member.getMemberTypeValue());
            param.setBirthday(DateUtil.getDate(member.getBirthday()));
            param.setDepartment(member.getDepartmentName());
            param.setPosition(member.getPositionName());
            param.setInstituteId(member.getInstituteId());
            param.setInstituteName(member.getInstituteName());
            param.setAge(member.getAge());

            List<ExtendFieldValue> fieldValuesList = member.getFieldValuesList();
            if (CollUtil.isNotEmpty(fieldValuesList)) {
                List<MemberFieldParam> fieldParams = new ArrayList<>(fieldValuesList.size());
                fieldValuesList.forEach(var -> {
                    MemberFieldParam memberFieldParam = new MemberFieldParam();
                    memberFieldParam.setId(var.getId());
                    memberFieldParam.setOrgId(var.getOrgId());
                    memberFieldParam.setName(var.getName());
                    memberFieldParam.setType(var.getMemberTypeValue());
                    memberFieldParam.setAttribute(var.getMemberTypeValue());
                    fieldParams.add(memberFieldParam);
                });
                param.setFieldValues(fieldParams);
            }

            List<LabelValue> labelsList = member.getLabelValuesList();
            if (CollUtil.isNotEmpty(labelsList)) {
                List<MemberLabelParam> labelParams = new ArrayList<>(labelsList.size());
                labelsList.forEach(label -> {
                    MemberLabelParam memberLabelParam = new MemberLabelParam();
                    memberLabelParam.setId(label.getId());
                    memberLabelParam.setLabelId(label.getLabelId());
                    labelParams.add(memberLabelParam);
                });
                param.setLabels(labelParams);
            }
        }
        return param;
    }

    /**
     * request To GetMemberDetailParam
     *
     * @param request
     * @return
     */
    private GetMemberParam requestToGetMemberDetailParam(GetMemberRequest request) {
        GetMemberParam param = new GetMemberParam();
        // 联系人id
        param.setId(request.getId());
        // 组织id
        param.setOrgId(request.getOrgId());
        // 用户id
        param.setUserId(request.getUserId());
        return param;
    }

    /**
     * request To BatchDeleteMembersParam
     *
     * @param request
     * @return
     */
    private DeleteMembersParam requestToDeleteMembersParam(DeleteMembersRequest request) {
        DeleteMembersParam param = new DeleteMembersParam();
        // 联系人id
        param.setIds(request.getIdsList());
        return param;
    }

    /*@Override
    public void genSig(GenSigRequest request, StreamObserver<GenSigResponse> responseObserver) {
        GenSigResponse.Builder builder = GenSigResponse.newBuilder();
        String memberId = request.getMemberId();
        if (!ObjectId.isValid(memberId)) {
            builder.setStatus(RpcStatusResult.error("memberId格式错误"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        ServiceResult<String> result = memberService.genSig(memberId);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        builder.setMemberId(memberId);
        builder.setSig(result.getData());
        builder.setStatus(RpcStatusResult.success());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }*/

}
